<?php
namespace Home\Model;
use  Think\Model;
class UsersModel extends Model{
      
  //登录 other用于登录时的部分数据更新
  public function login($mobile_phone,$password,$other=array())
  {
  	   $Users=M('Users');
  	   $fd_info=$Users->field('ec_salt,visit_count')->where("mobile_phone='$mobile_phone'")->find();
  	   if(!$fd_info)
  	   	{return false;}

       $data=array();
       if(empty($fd_info['ec_salt']))
       {
         $data['u.mobile_phone']=$mobile_phone;
         $data['u.password']=md5($password);

         //连表查询，防止旅行社不存在的情况
         $field="u.img_str,u.user_id,u.user_name,u.img,u.token,u.utype,u.mobile_phone,u.end_mshop_time,m.mshop_id,m.mshop_name";
         $info=$Users->alias('u')->join("left join ".C("DB_PREFIX")."mshop as m  on m.mshop_id=u.mshop_id")->field($field)->where($data)->find();  
         if($info)
         {
            $rd=rand(1,9999);
            $data=array();
            $data['ec_salt']=$rd;
            $data['password']=md5(md5($password).$rd);
            $where=array();
            $where['mobile_phone']=$mobile_phone;
            $status=$Users->where($where)->save($data);
         }
       }
       else
       {
         $data['u.mobile_phone']=$mobile_phone;
         $data['u.password']=md5(md5($password).$fd_info['ec_salt']);

         //连表查询，防止旅行社不存在的情况
         $field="u.img_str,u.user_id,u.user_name,u.img,u.token,u.utype,u.mobile_phone,u.end_mshop_time,m.mshop_id,m.mshop_name";
         $info=$Users->alias('u')->join("left join ".C("DB_PREFIX")."mshop as m  on m.mshop_id=u.mshop_id")->field($field)->where($data)->find();  
         


     
       }

       if($info)
       {
          $mshop_id=$info['mshop_id']?$info['mshop_id']:0;
          $mshop_name=$info['mshop_name']?$info['mshop_name']:'';
          $info['mshop_name']=$mshop_name;
          
          $token=$this->get_nonce(30);
          $now_time=gmtime();
          $expires_in=$now_time+3600*24*7;

          $other['token']=$token;
          $other['expires_in']=$expires_in;
          
          $other['last_time']=gmtime();
          $other['last_ip']=get_client_ip();
          
          $where=array();
          $where['user_id']=$info['user_id'];


          $other['visit_count']=$fd_info['visit_count']?intval($fd_info['visit_count'])+1:1;

          $status=$Users->where($where)->save($other);
  

          $info['token']=$token;
          $path='http://'.$_SERVER['HTTP_HOST'].'/'.__ROOT__.'/';
          $info['img']=$info['img']?$path.$info['img']:'';
          $info['img_str']=$info['img_str']?$info['img_str']:'';
        
          if(!$mshop_id)
          {
            $info['end_mshop_time']='';
          }

          

          //当日是否已选择旅行社
          $info['to_chose']=0;
          if($info['end_mshop_time']<gmtime()&&$info['utype']==2){$info['to_chose']=1;}

          unset($info['end_mshop_time']);
          return $info;
       }
       else
       {
       	  return false;
       }
        
  }


  //token获取用户信息
  public function get_userinfo($token)
  {
       $Users=M('Users');
       $field="user_id,user_name,img,token,utype,mobile_phone,mshop_id,end_mshop_time,ec_salt,user_rank,rank_points";
       $where="token='$token' and expires_in>".gmtime();
       $row=$Users->field($field)->where($where)->find(); 
       if(!$row)return false;

       $info=$row;
       unset($info['user_rank']);
       unset($info['rank_points']);


        
       $DB_PREFIX=C('DB_PREFIX');
   /* 判断是否是特殊等级，可能后台把特殊会员组更改普通会员组 */
        if ($row['user_rank'] > 0) {
            $sql = "SELECT special_rank from " . $DB_PREFIX . "user_rank where rank_id='$row[user_rank]'";
            $ar_res = M()->query($sql);
            $res=$ar_res[0];
            if ($res['special_rank'] === '0' || $res['special_rank'] === null) {
                $sql = "update " . $DB_PREFIX. "users set user_rank='0' where user_id='$row[user_id]'";
                M()->execute($sql);
                $info['user_rank'] = 0;
                $info['discount'] = 1;
            }
        }
        /* 取得用户等级和折扣 */
        if ($row['user_rank'] == 0) {
            // 非特殊等级，根据等级积分计算用户等级（注意：不包括特殊等级）
            $sql = 'SELECT rank_id, discount FROM ' . $DB_PREFIX. "user_rank WHERE special_rank = '0' AND min_points <= " . intval($row['rank_points']) . ' AND max_points > ' . intval($row['rank_points']);
             $ar_row = M()->query($sql);
             $row = $ar_row[0];
            if ($row) {
                $info['user_rank'] = $row['rank_id'];
                $info['discount'] = $row['discount'] / 100.00;
            } else {
                $info['user_rank'] = 0;
                $info['discount'] = 1;
            }
        }
        //  else {
        //     // 特殊等级
        //     $sql = 'SELECT rank_id, discount FROM ' . $DB_PREFIX . "user_rank WHERE rank_id = '$row[user_rank]'";
        //      $ar_row = M()->query($sql);
        //      $row = $ar_row[0];
        //     if ($row) {
        //         $info_user[0]['user_rank'] = $row['rank_id'];
        //         $info_user[0]['discount'] = $row['discount'] / 100.00;
        //     } else {
        //         $info_user[0]['user_rank'] = 0;
        //         $info_user[0]['discount'] = 1;
        //     }
        // }


       return $info;  
   }
  //旅行社选择是否过期
  public function guideIsmshop($user_id)
  {
       $Users=M('Users');
       $field="user_id,user_name";
       $where="user_id='$user_id' and end_mshop_time>".time();
       $info=$Users->field($field)->where($where)->find();

       return $info;  
   }
   /**
     * 更新用户红包、用户等级--app接口 实时更新，接口无用
     *
     * @access  public
     * @return  void
     */
    public function update_user_info($user_id) {				
        if (!$user_id) {
            return false;
        }

        $DB_PREFIX=C('DB_PREFIX');
          /* 查询会员信息 */
        $time = time();
        $sql = 'SELECT u.utype,u.user_id,u.user_money,u.email, u.pay_points, u.user_rank, u.rank_points, ' .
                ' IFNULL(b.type_money, 0) AS user_bonus, u.last_login, u.last_ip' .
                ' FROM ' . $DB_PREFIX . 'users AS u ' .
                ' LEFT JOIN ' . $DB_PREFIX . 'user_bonus AS ub' .
                ' ON ub.user_id = u.user_id AND ub.used_time = 0 ' .
                ' LEFT JOIN ' . $DB_PREFIX . 'bonus_type AS b' .
                " ON b.type_id = ub.bonus_type_id AND b.use_start_date <= '$time' AND b.use_end_date >= '$time' " .
                " WHERE u.user_id = '$user_id'";
        $info_user=M()->query($sql);

        $row=$info_user[0];

        if($info_user)
        {
        	  /* 判断是否是特殊等级，可能后台把特殊会员组更改普通会员组 */
            if ($row['user_rank'] > 0) {
                $sql = "SELECT special_rank from " . $DB_PREFIX . "user_rank where rank_id='$row[user_rank]'";
                $ar_res = M()->query($sql);
                $res=$ar_res[0];
                if ($res['special_rank'] === '0' || $res['special_rank'] === null) {
                    $sql = "update " . $DB_PREFIX. "users set user_rank='0' where user_id='$row[user_id]'";
                    M()->execute($sql);
                    $row['user_rank'] = 0;
                }
            }
            /* 取得用户等级和折扣 */
            if ($row['user_rank'] == 0) {
                // 非特殊等级，根据等级积分计算用户等级（注意：不包括特殊等级）
                $sql = 'SELECT rank_id, discount FROM ' . $DB_PREFIX. "user_rank WHERE special_rank = '0' AND min_points <= " . intval($row['rank_points']) . ' AND max_points > ' . intval($row['rank_points']);
                 $ar_row = M()->query($sql);
                 $row = $ar_row[0];
                if ($row) {
                    $info_user[0]['user_rank'] = $row['rank_id'];
                    $info_user[0]['discount'] = $row['discount'] / 100.00;
                } else {
                    $info_user[0]['user_rank'] = 0;
                    $info_user[0]['discount'] = 1;
                }
            } else {
                // 特殊等级
                $sql = 'SELECT rank_id, discount FROM ' . $DB_PREFIX . "user_rank WHERE rank_id = '$row[user_rank]'";
                 $ar_row = M()->query($sql);
                 $row = $ar_row[0];
                if ($row) {
                    $info_user[0]['user_rank'] = $row['rank_id'];
                    $info_user[0]['discount'] = $row['discount'] / 100.00;
                } else {
                    $info_user[0]['user_rank'] = 0;
                    $info_user[0]['discount'] = 1;
                }
            }

            return $info_user[0];
        }
        else
        {
        	return false;
        }

    }

      /**
     * 重新计算购物车中的商品价格：目的是当用户登录时享受会员价格，当用户退出登录时不享受会员价格
     * 如果商品有促销，价格不变
     *更新购物车
     * @access  public
     * @return  void
     */
   public  function recalculate_price($session) {
        $user_id=$session['user_id'];
        if (!$user_id) {
            return false;
        }
        $DB_PREFIX=C('DB_PREFIX');

        /* 取得有可能改变价格的商品：除配件和赠品之外的商品 */
        $sql = 'SELECT c.rec_id, c.goods_id, c.goods_attr_id, g.promote_price, g.promote_start_date, c.goods_number,' .
                "g.promote_end_date, IFNULL(mp.user_price, g.shop_price * '$session[discount]') AS member_price " .
                ",g.is_shipping as g_is_shipping,g.cat_id as g_cat_id  ".
                'FROM ' . $DB_PREFIX . 'cart AS c ' .
                'LEFT JOIN ' . $DB_PREFIX . 'goods AS g ON g.goods_id = c.goods_id ' .
                "LEFT JOIN " . $DB_PREFIX . "member_price AS mp " .
                "ON mp.goods_id = g.goods_id AND mp.user_rank = '" . $session['user_rank'] . "' " .
                "WHERE c.user_id = '" .$user_id . "' AND c.parent_id = 0 AND c.is_gift = 0 AND c.goods_id > 0 " .
                "  AND c.extension_code <> 'package_buy'";
                // ." AND c.rec_type = '" . CART_GENERAL_GOODS";// 购物车商品类型;0普通;1团够;2拍卖;3夺宝奇兵

        $res = M()->query($sql);

        
        if(!$res)return false;

        foreach ($res AS $row) {
            $attr_id = empty($row['goods_attr_id']) ? array() : explode(',', $row['goods_attr_id']);


            $goods_price = D('GoodsBase')->get_final_price($session,$row['goods_id'], $row['goods_number'], true, $attr_id);
            $is_shipping=$row['g_is_shipping']?$row['g_is_shipping']:0;
               /* 计算商品的佣金 */
             $profit_rate = D('Category')->get_cat_rate( $row['g_cat_id']);
             $profit_rate =$profit_rate?$profit_rate:0;

            $goods_sql = "UPDATE " . $DB_PREFIX . "cart SET goods_price = '$goods_price',is_shipping='$is_shipping',profit_rate='$profit_rate' " .
                    "WHERE  goods_id = '" . $row['goods_id'] . "' AND user_id = '" . $user_id . "' AND rec_id = '" . $row['rec_id'] . "'";

            M()->execute($goods_sql);
        }

        /* 删除赠品，重新选择 */
        M()->execute('DELETE FROM ' . $DB_PREFIX .
                "cart WHERE user_id = '" . $user_id . "' AND is_gift > 0");
    }


      /**
     * 生成一串随机字符
     * @access  protected
     * @param   int     $num    字符数量
     * @return  array
     */
     protected function get_nonce($num=10) {
        $str="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        
        $nonce='';
        for ($i=0; $i <$num; $i++) { 
            $rd=rand(0,61);
            $nonce.=substr($str, $rd,1);
        }
        return $nonce;
    }
 /**
     *  添加或更新指定用户收货地址
     *
     * @access  public
     * @param   array       $address
     * @return  bool
     */
   public function update_address($address) {
        $address_id = intval($address['address_id']);
        $user_id = intval($address['user_id']);

        unset($address['address_id']);
        $user_address =M('user_address');

        $where['user_id'] = $address['user_id'];

        $address['best_time']=gmtime();
        if ($address_id > 0) {
           unset($address['user_id']);
            /* 更新指定记录 */
            $condition['address_id'] = $address_id;
            $condition['user_id'] = $user_id;
            $status=$user_address->where($condition)->save($address);
            if(!$status) {return false;}
        } else {
            /* 插入一条新记录 */
            $address_id=$user_address->add($address);
              if(!$address_id){return false;}
            
            $u_address_id=M('users')->where($where)->getField('address_id');
            if (!$u_address_id) {  
                /* 更新指定记录 */
                $condition=array();
                $condition['address_id'] = $address_id;
                M('users')->where($where)->save($condition);
            }

        }

        return $address_id;
    }
	


    /**
     * 取得收货人地址列表
     * @param   int     $user_id    用户编号
     * @param   int     $id         收货地址id
     * @return  array
     */
    public function get_consignee_list($user_id, $id = 0, $num = 10, $start = 0) {
        $field="address_id,consignee,province,city,district,address,mobile,zipcode";
        if ($id) {
            $where['address_id'] = $id;
            return M('user_address')->field($field)->where($where)->find($where);
        } else {            
            $where['user_id'] = $user_id;
            return M('user_address')->field($field)->where($where)->order('address_id')->limit($start,$num)->select($where);
        }
    }

 /**
     *  获取用户指定范围的订单列表
     *
     * @access  public
     * @param   int         $user_id        用户ID号
     * @param   int         $pay            订单状态，0未付款，1全部，2待发货,3已发货,4退货，默认1
     * @param   int         $num            列表最大数量
     * @param   int         $start          列表起始位置
     * @return  array       $order_list     订单列表
     *$value['handler']操作提示  0-错误订单 1-待付款 2-待发货 3-待收货  4-已结束订单  5-审核中
     */
    function get_user_orders($user_id, $pay = 1, $num = 10, $start = 0) {
        /* 取得订单列表 */


        $arr = array();

        if ($pay == 1) {
            $pay = '';
        }
        else if($pay ==2 ){
            
             $pay =  " AND   order_status=1 " .
                " AND   shipping_status in ('0','3') " .
               " AND ( pay_status=2 OR p.is_cod =1 ) and return_status=0 ";//is_cod
              
        } 
         else if($pay ==3 ){
            $pay = " AND order_status =5 and return_status=0 " .
               " AND shipping_status=1 ";
        } else if($pay ==4 ){
            $pay = " and (return_status>0 or order_status=4)  " ;
        } else {
            $pay = ' and order_status<2 and return_status=0 and pay_status =0 ';
        }
       
       $DB_PREFIX=C('DB_PREFIX');


        $sql = "SELECT o.money_paid,o.order_amount,o.bonus,o.commission,o.return_status,o.mshop_id,o.shipping_time,o.shipping_fee,order_id, order_sn, shipping_id, order_status, shipping_status, pay_status, add_time, " .
                "(goods_amount + shipping_fee + insure_fee + o.pay_fee + pack_fee + card_fee + tax - discount) AS total_fee " .
                " FROM " . $DB_PREFIX .
                "order_info o left join " . $DB_PREFIX ."payment p on o.pay_id=p.pay_id WHERE is_deleted=0 and user_id = '$user_id' " . $pay . " ORDER BY add_time DESC LIMIT $start , $num";

        $res = M()->query($sql);  //总价减红包金额

        // print_r($sql );exit();

        foreach ($res as $key => $value) {
 
             @$value['handler']=0;
            if($value['return_status']>0)
            {
               @$value['handler']=5;
            }
            else if ($value['order_status'] == 2 || $value['order_status'] == 4) {
               @$value['handler']=4;
            } 
            else if ($value['order_status'] == 5) {
               @$value['handler'] =3;

                /* 对配送状态的处理 */
                if ($value['shipping_status'] == 1) {
                     $shop_config=M('shop_config');
                    $unfrozen_day=$shop_config->where("code='unfrozen_day'")->getField('value');
                    $delivery_day=floatval($unfrozen_day)>0?$unfrozen_day:0;
                    if(($value['return_status']==0)&&$delivery_day)
                    {
                        //自动收货
                        $sh_time=$value['shipping_time']+3600*24*$delivery_day;
                        if($sh_time<=gmtime())
                        {

                            $sql=" update " . $DB_PREFIX ."order_info set shipping_status=2    where order_id='$value[order_id]'";
                            $res_sh = M()->execute($sql);
                            /* 记录日志 */
                            D('OrderBase')->order_action($value['order_sn'], $value['order_status'], 2, $value['pay_status'], '', $user_id);
                            //获得佣金_zhsf
                            $amount=$value['money_paid'];
                            if($value['mshop_id']&&$amount)
                            { 
                                
                                D('Mshop')->deal_profit($value['order_sn'],$value['mshop_id'],$amount,$value['shipping_fee'],$value['commission'],1);
                            }
                            $value['shipping_status']=2;
                            @$value['handler'] =4;

                        }
                    }


                }          
                elseif ($value['shipping_status'] == 2) {
                     @$value['handler']=4;
                }
            }
           elseif ($value['shipping_status'] == 3) {
                     @$value['handler']=2;
                }
            else {

                    if ($value['pay_status'] == 2) {
                       @$value['handler']=2;
                    } else {
                       @$value['handler']=1;
                    }   
             }

            $goods=D('order')->order_goods($value['order_id']);
            
            $order_num=0;
            foreach ($goods as  $gd_val) {
              $order_num+=$gd_val['goods_number'];
            } 

            //判断合计--减去红包的
            if($value['money_paid']>0)
            {
              $value['total_fee']=$value['money_paid'];
            }
            else if($value['order_amount']<$value['total_fee'])
            {
              $value['total_fee']=$value['order_amount'];
            }


            $value['shipping_status'] = ($value['shipping_status'] == 5) ? 3 : $value['shipping_status'];

            $bonus=$value['bonus']?$value['bonus']:0;
            $arr[] = array('order_id' => $value['order_id'],
            'order_sn' => $value['order_sn'],
            // 'img' => get_image_path(D('Order')->get_order_thumb($value['order_id'])),
            // 'order_time' => local_date(2, $value['add_time']),
            // 'shipping_id' => $value['shipping_id'],
            'shipping_fee' => $value['shipping_fee'],
            'total_fee' => price_format($value['total_fee'], false),
            // 'url' =>'http://'.$_SERVER['HTTP_HOST']. U('user/order_detail', array('order_id' => $value['order_id'])),
            'goods_count' => $order_num,
            'bonus' => $bonus,
            'goods' => $goods,
            'handler' => $value['handler']);


        }
        return $arr;
    }
     /**
     * 获取订单商品数量
     * @return type
     */
    public function get_order_goods_count($order_id) {
    
        $sql = "SELECT  COUNT(*) as count " .
            "FROM " . C('DB_PREFIX') . "order_goods AS o " .
            "LEFT JOIN " . C('DB_PREFIX') . "products AS p ON o.product_id = p.product_id " .
            "LEFT JOIN " . C('DB_PREFIX') . "goods AS g ON o.goods_id = g.goods_id " .
            "WHERE o.order_id = '$order_id' ";
        $res = M()->query($sql);
        return $res[0]['count'];
    }

/**
     *  获取指订单的详情
     *
     * @access  public
     * @param   int         $order_id       订单ID
     * @param   int         $user_id        用户ID
     *
     * @return   arr        $order          订单所有信息的数组
     */
    function get_order_detail($order_id, $user_id = 0) {



        $order_id = intval($order_id);
        if ($order_id <= 0) {
              return false;
        }
        $order = D('Order')->order_info($order_id);


        // print_r($order );exit();
        
        //切换手机订单的关联的支付方式
        // if ($order['mobile_pay'] <= 0) {
        //     //查询手机版支付方式的配置参数
        //     $sql = "SELECT pay_id, pay_config FROM " . C('DB_PREFIX') . 'touch_payment';
        //     $touch_payment_list = M()->query($sql);
        //     if (is_array($touch_payment_list)) {
        //         foreach ($touch_payment_list as $vo) {
        //             $touch_store = unserialize($vo['pay_config']);
        //             /* 取出已经设置属性的code */
        //             $touch_code_list = array();
        //             foreach ($touch_store as $key => $value) {
        //                 if ($value['name'] == 'relate_pay' && $value['value'] == $order['pay_id']) {
        //                     $touch_pay_id = $vo['pay_id'];
        //                 }
        //             }
        //         }
        //     }

        //     // 默认没有设置关联支付方式的
        //     if ($touch_pay_id <= 0) {
        //         $payment_list = D('Order')->available_payment_list(false, 0, true);
        //         /* 过滤掉余额支付方式 */
        //         if (is_array($payment_list)) {
        //             foreach ($payment_list as $key => $payment) {
        //                 if ($payment['pay_code'] != 'balance') {
        //                     $touch_pay_id = $payment['pay_id'];
        //                     break;
        //                 }
        //             }
        //         }
        //     }
          // 检查订单是否未付款和未发货 以及订单金额是否为0 和支付id是否为改变 
        //     if ($touch_pay_id > 0 && $order['pay_status'] == 1 && $order['shipping_status'] == 0 && $order['goods_amount'] > 0) {
        //         //查询电脑版支付方式
        //         $touch_payment_info = D('Order')->payment_info($touch_pay_id);
        //         $order['pay_id'] = $touch_payment_info['pay_id'];
        //         $order['pay_name'] = $touch_payment_info['pay_name'];

        //         $order_amount = $order['order_amount'] - $order['pay_fee'];
        //         $pay_fee = pay_fee($touch_pay_id, $order_amount);
        //         $order_amount += $pay_fee;

        //         $sql = "UPDATE " . $this->pre .
        //                 "order_info SET pay_id='$touch_pay_id', pay_name='$touch_payment_info[pay_name]', pay_fee='$pay_fee', order_amount='$order_amount', `mobile_pay` = '1'" .
        //                 " WHERE order_id = '$order_id'";
        //         M()->execute($sql);
        //     }
        // }

        //检查订单是否属于该用户
        if ($user_id > 0 && $user_id != $order['user_id']) {
          return false;
        }

        /* 只有未f付款才允许用户修改订单地址 */
        // if ($order['pay_status'] == 0) {
        //     $order['allow_update_address'] = 1; //允许修改收货地址
        // } else {
        //     $order['allow_update_address'] = 0;
        // }

         /* 如果是未付款状态，生成支付按钮 */

        //支付时间
       if ($order['pay_time'] > 0 ) {
            $order['pay_time_date'] = local_date(2,$order['pay_time']);
        }  else {
            $order['pay_time_date'] = '';
        }

        if ($order['shipping_time'] > 0 ) {
            $order['shipping_time_date'] = local_date(2,$order['shipping_time']);
        }  else {
            $order['shipping_time_date'] = '';
        }

        return $order;

    }

    /**
     * 根据商品id获取购物车中此id的数量
     */
    function get_goods_number($user_id,$goods_id,$product_id=0) {

       if($product_id)
       {
       // 查询
        $sql = "SELECT IFNULL(SUM(goods_number), 0) as number " .
                " FROM " .C('DB_PREFIX') .
                "cart WHERE user_id = '" .$user_id . "' AND rec_type != 'package_buy' AND product_id = " . $product_id;

       }
       else
       {
         // 查询
        $sql = "SELECT IFNULL(SUM(goods_number), 0) as number " .
                " FROM " .C('DB_PREFIX') .
                "cart WHERE user_id = '" .$user_id . "' AND rec_type != 'package_buy' AND goods_id = " . $goods_id;       
       }
        $list=M()->query($sql);
        $res = $list[0];
        return $res['number'];
    }

/**
     * 获得订单中的费用信息
     *
     * @access  public
     * @param   array   $order
     * @param   array   $goods
     * @param   array   $consignee
     * @param   bool    $is_gb_deposit  是否团购保证金（如果是，应付款金额只计算商品总额和支付费用，可以获得的积分取 $gift_integral）
     * @return  array
     */
    function order_fee($session,$order, $goods, $consignee) {

        $user_id=$session['user_id'];

        /* 初始化订单的扩展code */
        if (!isset($order['extension_code'])) {
            $order['extension_code'] = '';
        }

        // if ($order['extension_code'] == 'group_buy') {
        //     $group_buy = D('GroupBuyBase')->group_buy_info($order['extension_id']);
        // }

        $total = array('real_goods_count' => 0,
            'gift_amount' => 0,
            'goods_price' => 0,
            'market_price' => 0,
            'discount' => 0,
            'pack_fee' => 0,
            'card_fee' => 0,
            'shipping_fee' => 0,
            'shipping_insure' => 0,
            'integral_money' => 0,
            'bonus' => 0,
            'surplus' => 0,
            'cod_fee' => 0,
            'pay_fee' => 0,
            'tax' => 0);
        $weight = 0;

        /* 商品总价 */
        foreach ($goods AS $val) {
            /* 统计实体商品的个数 */
            if ($val['is_real']) {
                // $total['real_goods_count']++;
               //商品的所有数量
               $total['real_goods_count']=$total['real_goods_count']+$val['goods_number'];
            }
            $rec_ids[]=$val['rec_id'];

            $total['goods_price'] += $val['goods_price'] * $val['goods_number'];
            $total['market_price'] += $val['market_price'] * $val['goods_number'];
        }

        // print_r($total);exit();

        $total['saving'] = $total['market_price'] - $total['goods_price'];
        $total['save_rate'] = $total['market_price'] ? round($total['saving'] * 100 / $total['market_price']) . '%' : 0;

        $total['goods_price_formated'] = price_format($total['goods_price'], false);
        $total['market_price_formated'] = price_format($total['market_price'], false);
        $total['saving_formated'] = price_format($total['saving'], false);

        /* 折扣 */
        // if ($order['extension_code'] != 'group_buy') {
        //     $discount = model('Order')->compute_discount();
        //     $total['discount'] = $discount['discount'];
        //     if ($total['discount'] > $total['goods_price']) {
        //         $total['discount'] = $total['goods_price'];
        //     }
        // }
        // $total['discount_formated'] = price_format($total['discount'], false);

        /* 税额 */
        // if (!empty($order['need_inv']) && $order['inv_type'] != '') {
        //     /* 查税率 */
        //     $rate = 0;
        //     $invoice_type = C('invoice_type');
        //     foreach ($invoice_type['type'] as $key => $type) {
        //         if ($type == $order['inv_type']) {
        //             $rate = floatval($invoice_type['rate'][$key]) / 100;
        //             break;
        //         }
        //     }
        //     if ($rate > 0) {
        //         $total['tax'] = $rate * $total['goods_price'];
        //     }
        // }
        // $total['tax_formated'] = price_format($total['tax'], false);

        /* 包装费用 */
        // if (!empty($order['pack_id'])) {
        //     $total['pack_fee'] = pack_fee($order['pack_id'], $total['goods_price']);
        // }
        // $total['pack_fee_formated'] = price_format($total['pack_fee'], false);

        /* 贺卡费用 */
        // if (!empty($order['card_id'])) {
        //     $total['card_fee'] = card_fee($order['card_id'], $total['goods_price']);
        // }
        // $total['card_fee_formated'] = price_format($total['card_fee'], false);

        /* 红包 */

        if (!empty($order['bonus_id'])) {
            $bonus = D('Order')->bonus_info($order['user_id'],$order['bonus_id']);
            $total['bonus'] = $bonus['type_money'];
        }
        $total['bonus_formated'] = price_format($total['bonus'], false);

        /* 线下红包 */
        if (!empty($order['bonus_kill'])) {
            $bonus = D('Order')->bonus_info(0, $order['bonus_kill']);
            $total['bonus_kill'] = $order['bonus_kill'];
            $total['bonus_kill_formated'] = price_format($total['bonus_kill'], false);
        }



        /* 配送费用 */
        $shipping_cod_fee = NULL;


        if ($order['shipping_id'] > 0 && $total['real_goods_count'] > 0) {
            $region['country'] = $consignee['country'];
            $region['province'] = $consignee['province'];
            $region['city'] = $consignee['city'];
            $region['district'] = $consignee['district'];
            $shipping_info = D('order')->shipping_area_info($order['shipping_id'], $region);

            if (!empty($shipping_info)) {
                if ($order['extension_code'] == 'group_buy') {
                    $weight_price = D('Order')->cart_weight_price($rec_ids);
                } else {
                    $weight_price = D('Order')->cart_weight_price($rec_ids);
                }

                // 查看购物车中是否全为免运费商品，若是则把运费赋为零
                $sql = 'SELECT count(*) as count FROM ' .C('DB_PREFIX')
                . "cart WHERE  `user_id` = '" . $user_id 
                . "' AND `extension_code` != 'package_buy' AND `is_shipping` = 0";
                $list=M()->query($sql);
                $res = $list[0];
                $shipping_count = $res['count'];

                $total['shipping_fee'] = ($shipping_count == 0 AND $weight_price['free_shipping'] == 1) ? 0 : shipping_fee($shipping_info['shipping_code'], $shipping_info['configure'], $weight_price['weight'], $total['goods_price'], $weight_price['number']);

                if (!empty($order['need_insure']) && $shipping_info['insure'] > 0) {
                    $total['shipping_insure'] = shipping_insure_fee($shipping_info['shipping_code'], $total['goods_price'], $shipping_info['insure']);
                } else {
                    $total['shipping_insure'] = 0;
                }

                if ($shipping_info['support_cod']) {
                    $shipping_cod_fee = $shipping_info['pay_fee'];
                }
            }
        }

        $total['shipping_fee_formated'] = price_format($total['shipping_fee'], false);
        $total['shipping_insure_formated'] = price_format($total['shipping_insure'], false);

        // 购物车中的商品能享受红包支付的总额
        $bonus_amount = D('Order')->compute_discount_amount($rec_ids);


        // 红包和积分最多能支付的金额为商品总额
        $max_amount = $total['goods_price'] == 0 ? $total['goods_price'] : $total['goods_price'] - $bonus_amount;

        /* 计算订单总额 */
        if ($order['extension_code'] == 'group_buy' && $group_buy['deposit'] > 0) {
            $total['amount'] = $total['goods_price'];
        } else {
            $total['amount'] = $total['goods_price'] - $total['discount'] + $total['tax'] + $total['pack_fee'] + $total['card_fee'] +
                    $total['shipping_fee'] + $total['shipping_insure'] + $total['cod_fee'];

            // 减去红包金额
            $use_bonus = min($total['bonus'], $max_amount); // 实际减去的红包金额
            if (isset($total['bonus_kill'])) {
                $use_bonus_kill = min($total['bonus_kill'], $max_amount);
                $total['amount'] -= $price = number_format($total['bonus_kill'], 2, '.', ''); // 还需要支付的订单金额
            }

            $total['bonus'] = $use_bonus;
            $total['bonus_formated'] = price_format($total['bonus'], false);

            $total['amount'] -= $use_bonus; // 还需要支付的订单金额
            $max_amount -= $use_bonus; // 积分最多还能支付的金额
        }

        /* 余额 */
        $order['surplus'] = $order['surplus'] > 0 ? $order['surplus'] : 0;
        if ($total['amount'] > 0) {
            if (isset($order['surplus']) && $order['surplus'] > $total['amount']) {
                $order['surplus'] = $total['amount'];
                $total['amount'] = 0;
            } else {
                $total['amount'] -= floatval($order['surplus']);
            }
        } else {
            $order['surplus'] = 0;
            $total['amount'] = 0;
        }
        $total['surplus'] = $order['surplus'];
        $total['surplus_formated'] = price_format($order['surplus'], false);

        /* 积分 */
        $order['integral'] = $order['integral'] > 0 ? $order['integral'] : 0;
        if ($total['amount'] > 0 && $max_amount > 0 && $order['integral'] > 0) {
            $integral_money = value_of_integral($order['integral']);

            // 使用积分支付
            // $use_integral = min($total['amount'], $max_amount, $integral_money); // 实际使用积分支付的金额
            // $total['amount'] -= $use_integral;
            // $total['integral_money'] = $use_integral;
            // $order['integral'] = integral_of_value($use_integral);
        } else {
            $total['integral_money'] = 0;
            $order['integral'] = 0;
        }
        $total['integral'] = $order['integral'];
        $total['integral_formated'] = price_format($total['integral_money'], false);

        /* 保存订单信息 */
        // $_SESSION['flow_order'] = $order;

        // $se_flow_type = isset($_SESSION['flow_type']) ? $_SESSION['flow_type'] : '';

        /* 支付费用 */
        if (!empty($order['pay_id']) && ($total['real_goods_count'] > 0 || $se_flow_type != CART_EXCHANGE_GOODS)) {
            $total['pay_fee'] = pay_fee($order['pay_id'], $total['amount'], $shipping_cod_fee);
        }

        $total['pay_fee_formated'] = price_format($total['pay_fee'], false);

        $total['amount'] += $total['pay_fee']; // 订单总额累加上支付费用
        $total['amount_formated'] = price_format($total['amount'], false);

        /* 取得可以得到的积分和红包 */
        if ($order['extension_code'] == 'group_buy') {
            $total['will_get_integral'] = $group_buy['gift_integral'];
        } elseif ($order['extension_code'] == 'exchange_goods') {
            $total['will_get_integral'] = 0;
        } else {
            $total['will_get_integral'] = D('Order')->get_give_integral($rec_ids);
        }


        $total['will_get_bonus'] = $order['extension_code'] == 'exchange_goods' ? 0 : price_format(D('Order')->get_total_bonus($rec_ids), false);
        $total['formated_goods_price'] = price_format($total['goods_price'], false);
        $total['formated_market_price'] = price_format($total['market_price'], false);
        $total['formated_saving'] = price_format($total['saving'], false);

        if ($order['extension_code'] == 'exchange_goods') {
            $sql = 'SELECT SUM(eg.exchange_integral) ' .
                    'as sum FROM ' . C('DB_PREFIX') . 'cart AS c,' . C('DB_PREFIX') . 'exchange_goods AS eg ' .
                    "WHERE c.goods_id = eg.goods_id AND c.user_id= '" . $user_id . "' " .
                    "  AND c.rec_type = '4' " .
                    '  AND c.is_gift = 0 AND c.goods_id > 0 ' .
                    'GROUP BY eg.goods_id';
            $list = M()->query($sql);

            $res=$list[0];
            $exchange_integral = $res['sum'];
            $total['exchange_integral'] = $exchange_integral;
        }

        return $total;
    }
    /**
     * 取得用户当前可用红包
     * @param   int     $user_id        用户id
     * @param   float   $goods_amount   订单商品金额
     * @return  array   红包数组
     */
    function user_bonus_list($user_id, $num = 30, $start = 0) {
        $day = getdate();
        $today = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);

        $sql = "SELECT  b.bonus_id,b.order_id,t.type_name, t.type_money,t.use_start_date, t.use_end_date, t.min_goods_amount " .
                "FROM " . C('DB_PREFIX') . "bonus_type AS t," .//b.bonus_sn,t.type_id,
                C('DB_PREFIX'). "user_bonus AS b " .
                "WHERE t.type_id = b.bonus_type_id " .
                "AND b.user_id = '$user_id' ". " order by b.bonus_id desc ,t.use_start_date desc  LIMIT $start , $num";

        $list= M()->query($sql);

        foreach ($list as $key => &$value) {
          $value['past_date']=0;
          if($value['use_end_date']<$today)
          {$value['past_date']=1;}//过期

           if($value['order_id'])//已使用
           {$value['past_date']=1;}


           // $value['not_date']=0;
          // if($value['use_start_date']>$today)
          // {$value['not_date']=1;}//未到期
            $value['use_start_date'] = local_date(1, $value['use_start_date']);
            $value['use_end_date'] = local_date(1, $value['use_end_date']);

        }
        return $list;
    }



}
?>
